// --------------------------------------------首页页面-----------------------------------------------
import React, { useState, useEffect } from "react";
import { Swiper, Toast, Image, Input } from "antd-mobile";
import styles from "../style/home.module.css";
import { useNavigate } from "react-router-dom";
// 图片需要根据实际路径导入
import searchIcon from "../img/fangbigjing.png";
import bigIcon1 from "../img/zhoubian.png";
import bigIcon2 from "../img/lingshi.png";
import bigIcon3 from "../img/yule.png";
import hotIcon from "../img/hot.png";
import navIcon1 from "../img/one.png";
import navIcon2 from "../img/fours.png";
import navIcon3 from "../img/10019.png";
import navIcon4 from "../img/twos.png";
import navIcon5 from "../img/threes.png";
import { home } from "../api/home";

/**
 * 首页组件
 */
function HomePage() {
  // 定义商品数据接口
  interface Product {
    id: number;
    title?: string;           // 商品标题
    synopsis?: string;        // 商品简介
    price: number | string;   // 商品价格
    original_price?: number | string;  // 商品原价
    img?: string;             // 商品图片
  }
  
  // 从本地存储获取用户数据
  const user = JSON.parse(localStorage.getItem("user") || "null");
  console.log(user?.data?.token, "请求头token");
  console.log(user?.data?.id, "请求id");
  
  // 定义轮播图数据状态
  const [swiperData, setSwiperData] = useState<{ img?: string }[]>([]);
  // 从轮播图数据中提取图片路径
  const imagePaths = swiperData.map((item) => item.img);
  
  // 定义分类数据接口
  interface TypeItem {
    id: number;
    img: string;
    title: string;
  }
  
  // 定义分类数据状态
  const [typeList, setTypeList] = useState<TypeItem[]>([]);
  console.log(imagePaths, "imagePaths");
  console.log(swiperData, "swiperData");
  
  // 定义商品列表状态
  const [shopList, setShopList] = useState<Product[]>([]);
  // 路由导航
  const navigate = useNavigate();
  
  /**
   * 跳转到对应分类页面
   * @param id 分类ID
   */
  const jump = (id: number) => {
    navigate("/classify");
    localStorage.setItem("id", id.toString());
  };
  
  /**
   * 组件挂载后获取数据
   */
  useEffect(() => {
    /**
     * 获取商品列表数据
     */
    const fetchShopList = async () => {
      try {
        // 检查用户数据和token是否存在
        if (!user?.data?.token || !user?.data?.id) {
          console.error("用户数据不存在或 token/id 为空");
          return;
        }
        
        // 发送请求获取数据
        const res = await home({
          headers: {
            token: user.data.token,
            id: user.data.id,
          },
        });
        console.log("请求结果:", res);
        
        // 检查返回数据格式是否符合预期
        if (res.data && Array.isArray(res.data.data.list)) {
          setShopList(res.data.data.list);        // 设置商品列表数据
          setSwiperData(res.data.data.swiper);    // 设置轮播图数据
          setTypeList(res.data.data.type);        // 设置分类数据
        } else {
          console.error("返回数据格式不符合预期:", res.data);
          setShopList([]);
        }
      } catch (error) {
        console.error("获取推荐商品失败:", error);
      }
    };
    
    // 用户ID存在时才获取数据
    user?.data?.id && fetchShopList();
  }, [user?.data?.id, user?.data?.token]);
  
  /**
   * 跳转到商品详情页
   * @param id 商品ID
   */
  const handleItemClick = (id: string | number) => {
    localStorage.setItem("productId", id.toString());
    // 跳转到详情页面
    navigate("/detail");
  };
  
  return (
    <div className={styles.big}>
      {/* 顶部背景和轮播图 */}
      <div className={styles.bigs}>
        {/* 搜索框 - 点击跳转到搜索页面 */}
        <div className={styles.search} onClick={() => navigate("/search")}>
          <Input placeholder="请输入您要搜索的内容" />
          <img src={searchIcon} alt="搜索" />
        </div>

        {/* 轮播图 - 使用Swiper组件 */}
        <div className={styles.banner}>
          <Swiper
            autoplay // 自动播放
            loop // 循环播放
            indicator={(total, current) => (
              // 自定义指示点
              <div className={styles.dot}>
                {imagePaths.map((_, index) => (
                  <div
                    key={index}
                    style={{
                      backgroundColor: current === index ? "#FF8D1A" : "#ffffff",
                    }}
                  />
                ))}
              </div>
            )}
          >
            {imagePaths.map((img, index) => (
              <Swiper.Item key={index}>
                <Image src={img} alt={`banner-${index}`} />
              </Swiper.Item>
            ))}
          </Swiper>
        </div>
      </div>
      
      {/* 分类图标 - 点击跳转到对应分类 */}
      <div className={styles.classIcon}>
        {typeList.map((type) => (
          <div
            className={styles.icon_item}
            key={type.id}
            onClick={() => jump(type.id)}
          >
            <div className={styles.icon_img}>
              <img src={type.img} alt={type.title} />
            </div>
            <p>{type.title}</p>
          </div>
        ))}
      </div>

      {/* 分类大图标 - 点击显示提示 */}
      <div className={styles.bigIcon}>
        <div
          className={styles.bigIcons}
          onClick={() => {
            Toast.show({
              content: "敬请期待吧",
              icon: "success",
            });
          }}
        >
          <img src={bigIcon1} alt="周边" />
        </div>
        <div className={styles.bigIcones}>
          <img
            src={bigIcon2}
            alt="零食"
            onClick={() => {
              Toast.show({
                content: "敬请期待吧",
                icon: "success",
              });
            }}
          />
          <img
            src={bigIcon3}
            alt="娱乐"
            onClick={() => {
              Toast.show({
                content: "敬请期待吧",
                icon: "success",
              });
            }}
          />
        </div>
      </div>

      {/* 热销商品标题 */}
      <div className={styles.hot}>
        <img src={hotIcon} alt="热销" />
        <p>热销商品</p>
      </div>

      {/* 商品列表 - 点击跳转到商品详情 */}
      <div className={styles.shop}>
        {shopList.map((product) => (
          <div
            key={product.id}
            className={styles.shop_item}
            onClick={() => handleItemClick(product.id)}
          >
            <img src={product.img} alt={product.title} />
            <p>{product.title}</p>
            <span>{product.synopsis}</span>
            <div className={styles.items}>
              <p>￥{Number(product.price).toFixed(2)}</p>
              {product.original_price && (
                <del>￥{Number(product.original_price).toFixed(2)}</del>
              )}
            </div>
          </div>
        ))}
      </div>

      {/* 底部导航栏 */}
      <div className={styles.bottom}>
        <div className={styles.bottom_items}>
          <div>
            <img src={navIcon1} alt="首页" />
          </div>
          <p>首页</p>
        </div>
        <div
          className={styles.bottom_item}
          onClick={() => {
            localStorage.setItem("id", "99");
            navigate("/classify");
          }}
        >
          <div>
            <img src={navIcon2} alt="分类" />
          </div>
          <p>分类</p>
        </div>
        <div className={styles.punch} onClick={() => navigate("/clock")}>
          <div>
            <div className={styles.punches}>
              <div className={styles.punchs}>
                <img src={navIcon3} alt="打卡" />
              </div>
            </div>
          </div>
          <p>打卡</p>
        </div>
        <div
          className={styles.bottom_item}
          onClick={() => navigate("/shopcart")} >
          <div>
            <img src={navIcon4} alt="购物车" />
          </div>
          <p>购物车</p>
        </div>
        <div className={styles.bottom_item} onClick={() => navigate("/me")}>
          <div>
            <img src={navIcon5} alt="我的" />
          </div>
          <p>我的</p>
        </div>
      </div>
    </div>
  );
}

export default HomePage;